import java.util.*;

/**
 * @author LKQ
 * @date 2022/3/22 16:27
 * @description
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] grid = {{1, 0, 0}, {0, 0, 0}, {0, 0, 0}};
        System.out.println(solution.maxDistance(grid));
    }

    public int maxDistance(int[][] grid) {
        int n = grid.length;
        boolean[][] visited = new boolean[n][n];
        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        Queue<int[]> queue = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    queue.add(new int[]{i, j});
                }
            }
        }
        int size = queue.size();
        if (size == 0 || size == n * n) {
            return -1;
        }
        int cur = 1;
        while (!queue.isEmpty()) {
            int t = queue.size();
            while (t > 0) {
                int[] loc = queue.poll();
                int i = loc[0], j = loc[1];
                visited[i][j] = true;
                for (int k = 0; k < 4; k++) {
                    int ni = i + dirs[k][0], nj = j + dirs[k][1];
                    if (ni >= 0 && ni < n && nj >= 0 && nj < n && !visited[ni][nj]) {
                        grid[ni][nj] = cur;
                        visited[ni][nj] = true;
                        queue.add(new int[]{ni, nj});
                    }
                }
                t--;
            }
            cur++;
        }
        int max = 0;
        for (int[] ints : grid) {
            for (int j = 0; j < n; j++) {
                if (ints[j] > max) {
                    max = ints[j];
                }
            }
        }
        return max;
    }
}
